package com.wsh.security.service;

import com.wsh.utils.SecurityUtils;
import com.wsh.entity.sys.MenuEntity;
import com.wsh.entity.sys.UserEntity;
import com.wsh.sys.MenuService;
import com.wsh.sys.RoleMenuService;
import com.wsh.sys.RoleService;
import com.wsh.sys.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * 登陆身份认证
 * Author: wangsh
 * createAt: 2020/01/31
 */
@Component(value="CustomUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 菜单权限
     */
    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        UserEntity userEntity = userService.findUserByUsername(name);

        if (userEntity == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", name));
        }

        User user = new User(userEntity.getUsername(), userEntity.getPassword(), getAuthorities(userEntity.getRoleId()));

        return user;
    }

    /**  * 获取用户的角色权限,为了降低实验的难度，这里去掉了根据用户名获取角色的步骤     * @param    * @return   */
    private Collection<GrantedAuthority> getAuthorities(String roleId){
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();

        // 防止权限为空
        authList.add(new SimpleGrantedAuthority(roleService.getById(roleId).getPerimission()));
        // 超级管理员
        if (SecurityUtils.isAdmin(roleId)) {
            return authList;
        }


        // 非超级管理员进行权限查询
        String[] menusArr = roleMenuService.getMenusByRole(roleId).getMenus();

        List<MenuEntity> menuEntities = menuService.getBaseMapper().selectBatchIds(Arrays.asList(menusArr));
        menuEntities.stream().filter(e -> e.getRoleMark() != null).forEach((e) -> authList.add(new SimpleGrantedAuthority(e.getRoleMark())));


        return authList;
    }

}
